package com.koron.order.linepatrol.uav.excel;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.excel.util.StringUtils;
import com.koron.bean.base.Response;
import com.koron.order.linepatrol.satellite.excel.LineAnalysisEventListener;
import com.koron.order.linepatrol.uav.bean.VO.LinePatrolUnv;
import com.koron.order.linepatrol.uav.bean.VO.TypeGroup;
import com.koron.order.linepatrol.uav.bean.excel.LinePatrolExcel;
import com.koron.order.linepatrol.uav.converter.LinePatrolUnvConverter;
import com.koron.order.linepatrol.uav.mapper.LineUnvDefectPatrolDetailMapper;
import com.koron.order.linepatrol.uav.service.LineUnvDefectPatrolDetailService;
import com.koron.order.overhaul.bean.dto.Equipment;
import com.koron.order.risk.feign.LineEquipmentFeign;
import com.koron.order.risk.feign.dto.EquipmentParams;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.koron.ebs.mybatis.ADOConnection;
import org.koron.ebs.mybatis.SessionFactory;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ClassName: LinePatrolUnvExcelListener
 * @Description:
 * @Date: 2023/2/10
 * @Author: 李一辰
 * @Version: 1.0
 **/
@Slf4j
@AllArgsConstructor
public class LinePatrolUnvExcelListener extends LineAnalysisEventListener<LinePatrolExcel> {

    private final LineUnvDefectPatrolDetailService lineUnvDefectPatrolDetailService;

    private final LinePatrolUnvConverter linePatrolUnvConverter;

    private final LineEquipmentFeign equipmentFeign;
    private String defectId;
    // 每隔100条，然后清理list ，方便内存回收
    private static final int BATCH_COUNT = 100;
    // 要保存的数据
    private final List<LinePatrolUnv> linePatrolSatelliteList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

    private final List<TypeGroup> typeGroups = getTypeGroups();


    @Override
    public void invoke(LinePatrolExcel data, AnalysisContext context) {
        LinePatrolUnv linePatrolUnv = fillData(data);
        if (linePatrolUnv == null) {
            return;
        }
        linePatrolSatelliteList.add(linePatrolUnv);
        if (linePatrolSatelliteList.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            linePatrolSatelliteList.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        saveData();
        log.info("所有数据解析完成！");
    }

    private void saveData() {
        computeManageDept();
        ADOConnection.runTask(getCurrDs(), lineUnvDefectPatrolDetailService, "BatchInsert", Integer.class, linePatrolSatelliteList);
        log.info("存储数据库成功！");
    }

    private void computeManageDept() {
        List<String> ids = linePatrolSatelliteList.stream().map(LinePatrolUnv::getTowerId).collect(Collectors.toList());

        Response<List<EquipmentParams>> batchBaseParams = equipmentFeign.getBatchBaseParams(ids);
        if (CollUtil.isEmpty(batchBaseParams.getData())) {
            return;
        }

        List<EquipmentParams> data = batchBaseParams.getData();
        Map<String, EquipmentParams> deptMap = data.stream()
                .filter(e -> "管理部门".equals(e.getParamName()))
                .collect(Collectors.toMap(EquipmentParams::getEquipmentId, e -> e, (o1, o2) -> o1));
        for (LinePatrolUnv linePatrolUnv : linePatrolSatelliteList) {
            EquipmentParams params = deptMap.get(linePatrolUnv.getTowerId());
            linePatrolUnv.setBelongDeptId(params.getParamResult());
            linePatrolUnv.setBelongDept(params.getParamValue());
        }

    }
    private LinePatrolUnv fillData(LinePatrolExcel data) {
        if (data == null) {
            return null;
        }
        LinePatrolUnv linePatrolUnv = linePatrolUnvConverter.excelToEntity(data);

        linePatrolUnv.setDefectId(defectId);

        String lineName = linePatrolUnv.getEquipmentName();
        if (lineName == null) {
            fillError(data, 0, "线路名称不能为空");
        }
        Equipment line = getLineByName(linePatrolUnv.getEquipmentName());
        if (line == null) {
            fillError(data, 0, "线路：" + linePatrolUnv.getEquipmentName() + "不存在");
            return null;
        } else {
            linePatrolUnv.setEquipmentId(line.getId());
        }

        // 杆塔
        if (StrUtil.isEmpty(linePatrolUnv.getTower())) {
            fillError(data, 1, "杆塔不能为空");
            return null;
        }
        Equipment tower = getTowerByNameAndChildren(line.getName(), linePatrolUnv.getTower(), line.getChildren());
        if (tower == null) {
            fillError(data, 1, "杆塔：" + data.getTower() + "不存在");
            return null;
        } else {
            linePatrolUnv.setTowerId(tower.getId());
        }
        //缺陷部件
        if(StringUtils.isEmpty(linePatrolUnv.getDefectiveUnit()))
        {
            fillError(data,2,"缺陷部件不能为空");
            return null;
        }
        List<TypeGroup> unit = typeGroups.stream().filter(i -> i.getName().equals(linePatrolUnv.getDefectiveUnit())).collect(Collectors.toList());
        if(CollUtil.isEmpty(unit)){
            fillError(data,2,"缺陷部件"+linePatrolUnv.getDefectiveUnit()+"不存在");
            return null;
        }

        return linePatrolUnv;
    }


    public List<TypeGroup> getTypeGroups() {
        try (SessionFactory factory = new SessionFactory()) {
            factory.setDbEnv(getCurrDs());
            LineUnvDefectPatrolDetailMapper mapper = factory.getMapper(LineUnvDefectPatrolDetailMapper.class);
            List<TypeGroup> typeGroup = mapper.getTypeGroup();
            return typeGroup;
        }
    }
}
